<?php
/**
 * 活动优惠页面
 *
 *
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');
class discountsControl extends BaseHomeControl{

    /**
     * 活动优惠
     */
    public function indexOp(){
        //轮播板块信息
        $model_web_config = Model('web_config');
        $web_html = $model_web_config->getWebHtml('new_indexp',1);
        Tpl::output('web_html',$web_html);

        //明天8点
        $time1 = strtotime('+1 day',strtotime('8:00'));
        //明天9点
        $time2 = strtotime('+1 day',strtotime('9:00'));
        $model_xianshi_goods = Model('p_xianshi_goods');
        //限时特惠-即将开始
        $xianshi_item2 = $model_xianshi_goods->getXianshiGoodsCommendList(3,array(array('gt', $time1),array('lt', $time2),'and'));
        Tpl::output('xianshi_item2', $xianshi_item2);
        //限时特惠-正在进行
        $xianshi_item = $model_xianshi_goods->getXianshiGoodsCommendList(3);
        Tpl::output('xianshi_item', $xianshi_item);

        //拼团
        $where=array();
        $page=4;
        $order='goods_common.sale_count DESC';
        $table="p_pintuan_goods,p_pintuan,goods,goods_common";
        $where["p_pintuan_goods.state"]     = 1;
        $where["p_pintuan.state"]           = 1;
        $where["p_pintuan_goods.start_time"]= array('lt',TIMESTAMP);
        $where["p_pintuan_goods.end_time"]  = array('gt',TIMESTAMP);
        $on="p_pintuan_goods.pintuan_id=p_pintuan.pintuan_id,p_pintuan_goods.goods_id=goods.goods_id,goods.goods_commonid=goods_common.goods_commonid";
        $field="p_pintuan_goods.goods_id,p_pintuan_goods.goods_name,p_pintuan_goods.goods_price,p_pintuan_goods.pintuan_price,
    	p_pintuan_goods.store_id,p_pintuan_goods.start_time,p_pintuan_goods.end_time,p_pintuan_goods.min_num,p_pintuan.pintuan_name,p_pintuan.store_name,goods.goods_image,goods.evaluation_good_star,goods.goods_storage";
        $pintuan_list=Model()->table($table)->on($on)->where($where)->field($field)->order($order)->page($page)->select();
        $pintuan_list=$this->make_activity_list($pintuan_list,1);
        Tpl::output('pintuan_list', $pintuan_list);

        //砍价
        $where=array();
        $page=4;
        $order='goods_common.sale_count DESC';
        $table="p_kanjia_goods,p_kanjia,goods,goods_common";
        $on="p_kanjia_goods.kanjia_id=p_kanjia.kanjia_id,p_kanjia_goods.goods_id=goods.goods_id,goods.goods_commonid=goods_common.goods_commonid";
        $where["p_kanjia_goods.state"]     = 1;
        $where["p_kanjia.state"]           = 1;
        $where["p_kanjia_goods.start_time"]= array('lt',TIMESTAMP);
        $where["p_kanjia_goods.end_time"]  = array('gt',TIMESTAMP);
        $field="p_kanjia_goods.goods_id,p_kanjia_goods.goods_name,p_kanjia_goods.goods_price,p_kanjia_goods.kanjia_price,
    	p_kanjia_goods.store_id,p_kanjia_goods.start_time,p_kanjia_goods.end_time,p_kanjia_goods.min_num,p_kanjia.kanjia_name,p_kanjia.store_name,goods.goods_image,goods.evaluation_good_star,goods.goods_storage";
        $kanjia_list=Model()->table($table)->on($on)->where($where)->field($field)->order($order)->page($page)->select();
        $kanjia_list=$this->make_activity_list($kanjia_list,2);
        Tpl::output('kanjia_list', $kanjia_list);

        //常用分类
        $staple_cate_ids = array_column(Model('goods_class_staple')->getCounter(1,4,'gc_id_1'),'gc_id_1');
        $staple_cate = Model('goods_class')->getGoodsClassList(array('gc_id'=>array('in',$staple_cate_ids)),'gc_id,gc_name');
        Tpl::output('staple_cate', $staple_cate);

        Tpl::showpage('new/discounts','index_layout');
    }

    /**
     * 组装活动商品列表【图片地址、砍价/拼团销量】
     * @author Harris
     * @param  returnData 商品数组
     * @param  type 1为砍价2为拼团
     * @return array
     * */
    private function make_activity_list($list,$type=1){
        $cp=$list;
        $sale_count_list = $this->get_sale_count($type);
        $visit_count_list= $this->get_visit_count($type);
        $kanjiaPrice     = $this->get_kanjia_price($type);
        $qr_code         = $this->create_qrcode($list);
        foreach($cp as $k => $v){
            $list[$k]['goods_image'] = cthumb($v['goods_image']);
            $list[$k]['sale_count']  = $sale_count_list[$v['goods_id']]?$sale_count_list[$v['goods_id']]:0;
            $list[$k]['visit_count'] = $visit_count_list[$v['goods_id']]?$visit_count_list[$v['goods_id']]:0;
            $list[$k]['qr_code']     = $qr_code[$v['goods_id']]?$qr_code[$v['goods_id']]:'';
            if(2==$type){
                //计算已砍价格
                if(!empty($kanjiaPrice[$v['goods_id']])){
                    //已砍人数
                    $already_kanjia_count = $kanjiaPrice[$v['goods_id']]['now'];
                    $already_kanjia_price = array_sum(array_slice($kanjiaPrice[$v['goods_id']]['kan_price'],$already_kanjia_count));

                }else{
                    $already_kanjia_price = 0;
                }
                $list[$k]['already_kanjia_price']=$already_kanjia_price;
                //已砍百分之几
                $kanjia_percent = floor($already_kanjia_price/($v['goods_price']-$v['kanjia_price'])*100);
                $list[$k]['kanjia_percent']=$kanjia_percent;

                //砍价剩余时间时分秒
                $list[$k]['count_down']=$list[$k]['end_time']-time();

            }


        }
        return $list;
    }

    /**
     * 获取成功拼团/砍价数量统计
     * @author Harris
     * @param  type 1为砍价2为拼团
     * @return array
     * */
    private function get_sale_count($type=1){
        if($type==1){
            $list = Model()->query("select goods_id,count(*) from shopnc_order_pintuan where pay_time >0 and lock_state = 1 group by goods_id");
        }else if($type==2){
            $list = Model()->query("select goods_id,count(*) from shopnc_order_kanjia where pay_time >0 and lock_state = 1 group by goods_id");
        }
        $newlist = array();
        foreach($list->fetch_all() as $k => $v){
            $newlist[$v[0]] = $v[1];
        }
        return $newlist;
    }

    /**
     * 获取正在拼团/砍价数量统计
     * @author Harris
     * @param  type 1为砍价2为拼团
     * @return array
     * */
    private function get_visit_count($type=1){
        if($type==1){
            $list = Model()->query("select goods_id,count(*) from shopnc_order_pintuan where pay_time >0 and lock_state = 0 group by goods_id");
        }else if($type==2){
            $list = Model()->query("select goods_id,count(*) from shopnc_order_kanjia where pay_time >0 and lock_state = 0 group by goods_id");
        }
        $newlist=array();
        foreach($list->fetch_all() as $k => $v){
            $newlist[$v[0]]=$v[1];
        }
        return $newlist;
    }

    /**
     * 获取砍价信息
     */
    private function get_kanjia_price($type){
        if($type==2){
            $list=Model()->query("select goods_id,kanjia_price from shopnc_order_kanjia where pay_time >0 and lock_state = 0 group by goods_id");
        }else{
            return false;
        }
        $newlist=array();
        foreach($list->fetch_all() as $k => $v){
            $newlist[$v[0]]=json_decode($v[1],true);
        }
//        pr($newlist);
        return $newlist;
    }


    /**
     * 生成小程序二维码
     */
    private function create_qrcode($list){
        $access_token = Logic('applet_notice')->getAccessToken();

        $img_arr = array();
        foreach($list as $val){
            $applet_qr_code_cache = rkcache('applet_qr_code_'.$val['goods_id']);
            if(empty($applet_qr_code_cache)){
                $path="/pages/group-detail/index?goods_id=".$val['goods_id'];
                $data='{"path":"'.$path.'","width":"70"}';
                $url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".$access_token;
                $binary = getUrlContents($url,$data);
                //裁剪图片
                $src = imagecreatefromstring($binary);
                $x = 10;
                $y = 10;
                $width = 263;
                $height = 263;
                $final_width = 70;
                $final_height = 70;
                $new_image = imagecreatetruecolor($final_width, $final_height);
                imagecopyresampled($new_image, $src, 0, 0, $x, $y, $final_width, $final_height, $width, $height);
                ob_start ();
                imagejpeg($new_image);
                $image_data = ob_get_contents ();
                ob_end_clean ();
                $img_content = base64_encode($image_data);
                $img_content = 'data:image/jpeg;base64,'.$img_content;

                $img_arr[$val['goods_id']] = $img_content;

                wkcache('applet_qr_code_'.$val['goods_id'],$img_content);
            }else{
                $img_arr[$val['goods_id']] = $applet_qr_code_cache;
            }
        }
        return $img_arr;
    }

}